package com.haoshuang.zhouzhoubang.ui.adapter

import android.annotation.SuppressLint
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import androidx.recyclerview.widget.RecyclerView
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ItemOrderBinding
import com.haoshuang.zhouzhoubang.model.bean.OrderBean
import com.haoshuang.zhouzhoubang.ui.dialog.ShowRewardNoticeDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ShowServiceItemDialog
import com.haoshuang.zhouzhoubang.utils.DateTools
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseBindingHolder
import com.mufeng.libs.base.BaseBindingQuickAdapter
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.horizontal
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.visible
import com.mufeng.libs.utils.view.visibleOrGone

/**
 * 订单列表
 */
class OrderAdapter(data: MutableList<OrderBean>, private val status: Int) :
    BaseBindingQuickAdapter<OrderBean, ItemOrderBinding>(data) {

    private var countDownTimer: CountDownTimer? = null

    override fun onViewRecycled(holder: RecyclerView.ViewHolder) {
        super.onViewRecycled(holder)
        countDownTimer?.cancel()
        countDownTimer = null
    }

    /**
     * 服务中
     */
    private fun ItemOrderBinding.servicing(item: OrderBean) {
        tvNormal.visible()
        tvNormal.text = "服务中"
        ivNavigation.visible()
        tvContactWorker.visible()
        // 提交验收
        tvSubmitAcceptance.visible()
        // 上传服务中图片
        tvUploadImage.visible()
        if (item.is_team == "1") {
            if (item.user_status == "1" || item.user_status == "2") {
                ivCallPhone.visible()
            } else {
                ivCallPhone.gone()
            }
        } else {
            ivCallPhone.visible()
        }
        if (item.user_status == "3") {
            tvSubmitAcceptance.gone()
        } else {
            tvSubmitAcceptance.visible()
        }
    }

    /**
     * 待服务
     * @receiver ItemOrderBinding
     * @param item OrderBean
     */
    private fun ItemOrderBinding.setupUnService(item: OrderBean) {
        ivNavigation.visible()
        if (item.is_team == "1") {
            ivCallPhone.visibleOrGone(item.user_status == "1" || item.user_status == "2")
        } else {
            ivCallPhone.visible()
        }

        if (item.is_confirm != "1") {
            tvDfw.text = "待确认"
            tvDfw2.text = "待确认"
            tvContactWorker.gone()
            tvTaskAssignment.gone()
            tvUpdateTime.gone()
            tvContactCustomers.visible()
            tvCancelOrder.gone()
            tvConfirmService.gone()
        } else {
            tvDfw.text = "待服务"
            tvDfw2.text = "待服务"
            tvContactWorker.visible()
            tvTaskAssignment.visible()
            tvUpdateTime.visible()
            tvConfirmService.visible()
        }

        var isTimeOut = 0
        var time = item.residue_time
        if (item.is_confirm == "1") {
            tvConfirmService.visible()
            isTimeOut = item.is_overtime
            time = item.countdown.toString()
        } else {
            tvContactCustomers.visible()
            isTimeOut = item.is_residuetime
            time = item.residue_time
        }

        if (isTimeOut == 0) {
            // 正常 开始倒计时
            if (time.toLong() > 0) {
                bllToBeServed.visible()
                bllTimedOut.gone()
                countDownTimer =
                    object : CountDownTimer(
                        time.toLong() * 1000,
                        1000
                    ) {
                        override fun onTick(millisUntilFinished: Long) {
                            val s: String =
                                DateTools.millisecondsConvertToHMS(millisUntilFinished)
                            tvTime.text = s
                        }

                        override fun onFinish() {
                            bllToBeServed.visibleOrGone(false)
                            bllTimedOut.visibleOrGone(true)
                        }
                    }
                countDownTimer?.start()
            } else {
                bllToBeServed.gone()
                bllTimedOut.visible()
            }
        } else {
            bllToBeServed.gone()
            bllTimedOut.visible()
        }
    }

    override fun onBindViewHolder(holder: BaseBindingHolder, position: Int, item: OrderBean?) {
        if (item == null) return
        holder.getViewBinding<ItemOrderBinding>().apply {

            // 重点区域
            tvKeyArea.text = "重点区域: ${item.key_areas}"
            tvKeyArea.visibleOrGone(!item.key_areas.isNullOrEmpty())

            val list = mutableListOf<OrderBean.OrderTeamMember>()
            item.team_member?.forEach { member ->
                if (list.none { it.uid == member.uid }) {
                    list.add(member)
                }
            }
            tvTotalNum.text = "数量 x${item?.total_num.toString()}"
            val adapter = OrderTeamMemberAdapter(list)
            recyclerView.horizontal().adapter = adapter
            llTeamMember.visibleOrGone(item.team_member?.isNotEmpty() == true)
            ivPlatformOrder.visibleOrGone(item.is_platform_order == 1)
            llRewardView.clickWithTrigger {
                XPopup.Builder(context)
                    .asCustom(ShowRewardNoticeDialog(context))
                    .show()
            }
            llRewardView.visibleOrGone(item.base_reward_amount != null && 0.0 != item.base_reward_amount?.toDoubleOrNull())
            tvRewardMoney.text = "${item.base_reward_amount}元"
            tvUserName.text = item.real_name
            if (item.user_phone.length == 11) {
                tvPhone.text = item.user_phone.replaceRange(4, 7, "****")
            } else {
                tvPhone.text = item.user_phone
            }

            var layout_address = holder.getView<LinearLayout>(R.id.layout_address)
            if (item.hexiao_type == 2) {
                layout_address.visibility = View.GONE
                tvServiceTime.text = "核销时间：" + item.finish_time
            } else {
                tvServiceTime.text = "期待上门时间：" + item.service_time
                layout_address.visibility = View.VISIBLE
            }

            if (item.hourly_worker_time.isNullOrBlank()) {
                tvStoreName.text = "服务内容:${item.store_name}"
            } else {
                if (item.hourly_worker_time == "0") {
                    tvStoreName.text = "服务内容:${item.store_name}"
                } else {
                    tvStoreName.text =
                        "服务内容:${item.store_name} [${item.hourly_worker_time}小时]"
                }
            }
            tvAddress.text = item.base_address
            tvMark.text = item.mark
            tvPayPrice.text = "¥" + item.pay_price
            ivHead.load(item.user_avatar, R.mipmap.rl)

            // 订单类型
            if (item.show_status == "1") {
                ivOrderType.setImageResource(R.mipmap.taoc)
            } else if (item.show_status == "2") {
                ivOrderType.setImageResource(R.mipmap.tddd09)
            } else {
                ivOrderType.setImageResource(R.mipmap.grdd09)
            }

            // 订单角色
            when (item.user_status) {
                "1" -> {
                    ivOrderRole.visible()
                    ivOrderRole.setImageResource(R.mipmap.duizhang)
                }

                "2" -> {
                    ivOrderRole.visible()
                    ivOrderRole.setImageResource(R.mipmap.fzr)
                }

                "3" -> {
                    ivOrderRole.visible()
                    ivOrderRole.setImageResource(R.mipmap.dyy)
                }

                else -> {
                    ivOrderRole.gone()
                }
            }

            // 底部操作按钮的显示隐藏


            // 是否显示收款按钮
            if (item.is_need_pay == 0) {
                tvPayment.gone()
            } else {
                tvPayment.visible()
            }

            if (item.is_cart_order == 1) {
                tvServiceNum.text ="共"+ item.order_goods.size+"个服务项"
                tvServiceNum.click {
                    val list = item?.order_goods
                    if (list.isNullOrEmpty()){
                        return@click
                    }
                    XPopup.Builder(context)
                        .asCustom(ShowServiceItemDialog(context, list))
                        .show()
                }
            }else{
                tvServiceNum.text =""
            }

            when (item.status) {
                "0" -> {
                    // 待支付
                    tvNormal.visible()
                    tvNormal.text = "待支付"
                    ivNavigation.visible()
                    tvContactWorker.gone()
                    if (item.is_team == "1") {
                        ivCallPhone.visibleOrGone(item.user_status == "1" || item.user_status == "2")
                    } else {
                        ivCallPhone.visible()
                    }
                }

                "1" -> {
                    // 立即签到和已签到
                    if (item.is_confirm == "1" && item.user_status == "3") {
                        if (item.is_sign == 0) {
                            tvSign.visible()
                            tvSigned.gone()
                        } else {
                            tvSign.gone()
                            tvSigned.visible()
                        }
                    } else {
                        tvSign.gone()
                        tvSigned.gone()
                    }
                    // 待服务
                    setupUnService(item)
                }

                "2" -> {
                    // 进行中
                    servicing(item)
                }

                "3" -> {
                    viewPoint.visibleOrGone(item.is_done_check != "1")
                    // 已完成
                    tvNormal.visible()
                    tvNormal.text = "已完成"
                    tvContactWorker.gone()
                }

                "6" -> {
                    // 验收中
                    tvContactWorker.visible()
                    tvNormal.visible()
                    tvNormal.text = "验收中"
                    ivNavigation.gone()
                    ivCallPhone.gone()
                    // 验收码
                    tvAcceptanceQRCode.visible()
                }

                "10" -> {
                    // 上门中
                    tvNormal.visible()
                    tvNormal.text = "待确认服务"
                    ivNavigation.visible()
                    tvContactWorker.visible()
                    tvConfirmedService.visible()
                    if (item.is_team == "1") {
                        if (item.user_status == "1" || item.user_status == "2") {
                            ivCallPhone.visible()
                        } else {
                            ivCallPhone.gone()
                        }
                    } else {
                        ivCallPhone.visible()
                    }
                }
                // 退款
                else -> {
                    tvContactWorker.visible()
                    ivCallPhone.gone()
                    ivNavigation.gone()
                    if (item.progress == 0) {
                        viewPoint.visibleOrGone(item.is_done_check != "1")
                        //0不做处理1师傅已退款2师傅已拒绝3用户已取消4平台介入5平台已退款6平台已拒绝
                        tvNormal.visible()
                        tvContactWorker.gone()
                        tvNormal.text = when (item.is_deal_status) {
                            1 -> "师傅已退款"
                            2 -> "师傅已拒绝"
                            3 -> "平台介入"
                            5 -> "平台已退款"
                            6 -> "平台已拒绝"
                            else -> "已取消"
                        }
                        bllToBeServed.gone()
                        bllTimedOut.gone()
                        tvImmediateProcessing.gone()
                    } else {
                        tvNormal.gone()
                        if (item.is_overtime == 0) {
                            tvImmediateProcessing.visible()
                            bllToBeServed.visible()
                            tvDfw.text = "退款中"
                            tvDfw2.text = "退款中"
                            if (item.define_second > 0) {
                                var num = item.define_second * 1000
                                countDownTimer =
                                    object : CountDownTimer(num.toLong(), 1 * 1000) {
                                        @SuppressLint("SimpleDateFormat")
                                        override fun onTick(millisUntilFinished: Long) {
                                            val s: String =
                                                DateTools.millisecondsConvertToHMS(
                                                    millisUntilFinished
                                                )
                                            tvTime.text = s
                                        }

                                        override fun onFinish() {
                                            tvTime.setText("00:00:00")
                                            item.is_overtime = 1
                                            notifyItemChanged(holder.layoutPosition)
                                            bllTimedOut.visibleOrGone(true)
                                            tvImmediateProcessing.gone()
                                        }
                                    }
                                countDownTimer?.start()
                            } else {
                                bllTimedOut.visible()
                                bllToBeServed.gone()
                                tvImmediateProcessing.gone()
                            }
                        } else {
                            bllTimedOut.gone()
                            bllToBeServed.gone()
                            tvImmediateProcessing.gone()
                        }
                        if (item.user_status == "3") {
                            tvImmediateProcessing.gone()
                        } else {
                            tvImmediateProcessing.visible()
                        }
                    }
                }
            }

        }
    }
}
